package cn.edu.nju.software.action.category;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;

import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.storage.Category;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class GetCategoryOptionAction extends ActionSupport implements SessionAware {
	
	private Map<Integer, String> categories;
	private Map<String, Object> session;

	public Map<Integer, String> getCategories() {
		return categories;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public String execute() throws Exception {
		//前序深度优先遍历书籍分类
		DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) session.get(Constants.SESSION_ROOT_CATEGORY);
		Stack<DefaultMutableTreeNode> stack = new Stack<DefaultMutableTreeNode>();
		stack.push(rootNode);
		categories = new LinkedHashMap<Integer, String>();
		while (!stack.empty()) {
			DefaultMutableTreeNode currentNode = stack.peek();
			if (currentNode.isLeaf()) {
				DefaultMutableTreeNode nextSibling = currentNode.getNextSibling();
				stack.pop();
				if (nextSibling == null) {
					DefaultMutableTreeNode parent = (DefaultMutableTreeNode) currentNode.getParent();
					stack.pop();
					while (!parent.isRoot() && parent.getNextSibling()==null) {
						parent = (DefaultMutableTreeNode) parent.getParent();
						stack.pop();
					}
					if (!parent.isRoot()) {
						DefaultMutableTreeNode inNode = parent.getNextSibling();
						stack.push(inNode);
						addToMap(inNode);
					}
				} else {
					DefaultMutableTreeNode inNode = nextSibling;
					stack.push(inNode);
					addToMap(inNode);
				}
			} else {
				DefaultMutableTreeNode inNode = (DefaultMutableTreeNode) currentNode.getFirstChild();
				stack.push(inNode);
				addToMap(inNode);
			}
		}
		return SUCCESS;
	}
	
	private void addToMap(DefaultMutableTreeNode node) {
		Category category = (Category) node.getUserObject();
		StringBuilder name = new StringBuilder(category.getName());
		for (int i = 1; i < node.getLevel(); i++ ) {
			name.insert(0, "-");
		}
		categories.put(category.getCategoryID(), name.toString());
	}

}
